package com.gyy.socket;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;

/**
 * @Author: 李阳阳
 * @Description: socket通讯工具类
 * @Date: 2021/9/23 19:22
 */
public class SocketTest1 {

    private static Socket socket;
    private static final int TIMEOUT_CONNECT = 500;// 设置延时 大于这个数字 就直接返回连接不上 或者出现其他问题
    private static final int TIMEOUT_RECEIVE = 2000;
    private static InputStream mInStream;// 写入
    private static OutputStream mOutStream;// 输出
    private static PrintWriter printwriter;// 刷缓存

    /**
     *
     * 开启线程
     * @return
     */
    public static boolean initSocket(String ip, int port){

        if(socket == null) {
            socket = new Socket();
        }
        InetSocketAddress isa = new InetSocketAddress(ip, port);
        try {
            socket.connect(isa, TIMEOUT_CONNECT);
            mInStream = socket.getInputStream();
            mOutStream = socket.getOutputStream();
            printwriter = new PrintWriter(socket.getOutputStream(), true);
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    /**
     *
     * 发送数据信息
     *
     * @param data
     */
    public static void send(byte[] data) {
        try {
            mOutStream.write(data);
        } catch (IOException e) {
            e.printStackTrace();
        }

        printwriter.flush();
    }

    /**
     *
     * 接受数据信息
     *
     * @return
     */
    public static byte[] receive() {
        if (socket == null) {
            return null;
        }
        byte[] buff = null;
        try {
            long timeBefore = System.currentTimeMillis();
            int count = 0;
            while (count == 0) {
                count = mInStream.available();
                if (System.currentTimeMillis() - timeBefore > TIMEOUT_RECEIVE) {
                    return null;
                }
            }
            buff = new byte[count];
            mInStream.read(buff);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return buff;
    }

    /**
     *
     * 卸载这个套接字
     */
    public static void uninstallSocket() {
        if (socket == null)
            return;

        try {
            if (mInStream != null)
                mInStream.close();
            if (mOutStream != null)
                mOutStream.close();
            if (printwriter != null)
                printwriter.close();
            socket.close();
            socket = null;
        } catch (IOException e1) {
            e1.printStackTrace();
        }
    }


    public static void main(String[] args) {
        initSocket("127.0.0.1", 502);
        byte[] receive = receive();
        System.out.println("---------------");

    }
}
